package com.kinon.ceshiaccount.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.bean.OfflineData;
import com.kinon.ceshiaccount.bean.base.BaseBean;
import com.kinon.ceshiaccount.bean.urgent.U_SettletmentBean;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.util.SPManage;

import org.litepal.crud.DataSupport;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 佛祖保佑 永无BUG
 *
 * @author WangZhiYao
 * @date 2018/5/4
 */
public class UploadService extends Service {

    private Disposable mDisposable;
    private List<U_SettletmentBean> mOfflineData;
    private String mData;
    private int mStatus;
    private Call<BaseBean<OfflineData>> mUploadCall;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int timeInterval = SPManage.getInstance().getInt("TIME_INTERVAL", 60);
        startUpload(timeInterval);
        return super.onStartCommand(intent, flags, startId);
    }

    private void startUpload(int time) {
        final String token = SPManage.getInstance().getToken();
        mOfflineData = DataSupport.where("submit=?", "0").find(U_SettletmentBean.class);
        mData = new Gson().toJson(mOfflineData);
        mStatus = mOfflineData.size();
        mDisposable = Flowable.interval(0L, time, TimeUnit.SECONDS)
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        Log.w("WZY", String.valueOf(aLong));
                        uploadData(token, mData, mStatus);
                    }
                }).subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        mOfflineData = DataSupport.where("submit=?", "0")
                                .find(U_SettletmentBean.class);

                        mData = new Gson().toJson(mOfflineData);
                        Log.w("WZY", mData);
                        mStatus = mOfflineData.size();
                    }
                });
    }

    private void uploadData(String token, String data, int status) {
        try {
            mUploadCall = HttpManage.getRequestApi().uploadOfflineData(token, data, status);
            mUploadCall.enqueue(new Callback<BaseBean<OfflineData>>() {
                @Override
                public void onResponse(@NonNull Call<BaseBean<OfflineData>> call, @NonNull Response<BaseBean<OfflineData>> response) {
                    BaseBean<OfflineData> data = response.body();
                    if (data != null && data.isCode()) {
                        Log.w("TAG", data.toString());
                        List<String> ids = data.getData().getOrdernos();
                        for (String id : ids) {
                            U_SettletmentBean offlineData = DataSupport.where("orderno=?", id)
                                    .findFirst(U_SettletmentBean.class);
                            offlineData.setSubmit(1);
                            offlineData.save();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<BaseBean<OfflineData>> call, @NonNull Throwable t) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mUploadCall.isExecuted()) {
            mUploadCall.cancel();
            mUploadCall = null;
        }

        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
}
